#!/bin/bash
# 测试 CMDB API 功能

echo "=========================================="
echo "   CMDB API 功能测试"
echo "=========================================="
echo ""

# 测试项目创建
echo "📦 测试项目管理..."
RESULT=$(curl -s -X POST http://localhost:8000/api/projects/ \
  -H "Content-Type: application/json" \
  -d '{"name":"测试项目","description":"自动化测试"}')
if echo "$RESULT" | grep -q '"id"'; then
    echo "  ✅ 项目创建成功"
    PROJECT_ID=$(echo "$RESULT" | grep -o '"id":[0-9]*' | grep -o '[0-9]*')
else
    echo "  ❌ 项目创建失败"
fi

# 测试环境创建
echo "🌍 测试环境管理..."
RESULT=$(curl -s -X POST http://localhost:8000/api/environments/ \
  -H "Content-Type: application/json" \
  -d '{"name":"测试环境","env_type":"test","description":"自动化测试"}')
if echo "$RESULT" | grep -q '"id"'; then
    echo "  ✅ 环境创建成功"
else
    echo "  ❌ 环境创建失败"
fi

# 测试主机组创建
echo "📁 测试主机组管理..."
RESULT=$(curl -s -X POST http://localhost:8000/api/host-groups/ \
  -H "Content-Type: application/json" \
  -d '{"name":"测试主机组","description":"自动化测试"}')
if echo "$RESULT" | grep -q '"id"'; then
    echo "  ✅ 主机组创建成功"
    HOSTGROUP_ID=$(echo "$RESULT" | grep -o '"id":[0-9]*' | grep -o '[0-9]*')
else
    echo "  ❌ 主机组创建失败"
fi

# 测试主机创建
echo "💻 测试主机管理..."
RESULT=$(curl -s -X POST http://localhost:8000/api/hosts/ \
  -H "Content-Type: application/json" \
  -d "{\"name\":\"测试主机\",\"ip\":\"192.168.1.100\",\"port\":22,\"username\":\"root\",\"auth_type\":\"password\",\"password\":\"test123\",\"status\":\"unknown\"}")
if echo "$RESULT" | grep -q '"id"'; then
    echo "  ✅ 主机创建成功"
else
    echo "  ❌ 主机创建失败"
    echo "  错误: $RESULT"
fi

# 测试用户管理（Django自带）
echo "👤 测试用户管理..."
RESULT=$(curl -s http://localhost:8000/api/users/)
if echo "$RESULT" | grep -q '"count"'; then
    echo "  ✅ 用户API响应正常"
else
    echo "  ❌ 用户API异常"
fi

# 测试用户组管理（Django自带）
echo "👥 测试用户组管理..."
RESULT=$(curl -s http://localhost:8000/api/groups/)
if echo "$RESULT" | grep -q '"count"'; then
    echo "  ✅ 用户组API响应正常"
else
    echo "  ❌ 用户组API异常"
fi

echo ""
echo "=========================================="
echo "   📊 测试总结"
echo "=========================================="
echo ""
echo "查看创建的数据:"
echo "  curl http://localhost:8000/api/projects/"
echo "  curl http://localhost:8000/api/environments/"
echo "  curl http://localhost:8000/api/host-groups/"
echo "  curl http://localhost:8000/api/hosts/"
echo ""
echo "访问前端界面: http://localhost:8080"
echo ""
